package com.example.nophase.activity.finance;

import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.widget.Toolbar;

import com.example.nophase.R;
import com.example.nophase.activity.FlowRecordActivity;
import com.example.nophase.adapter.FinanceProjectListAdapter;
import com.example.nophase.api.RequstCommonApi;
import com.example.nophase.base.BaseActivity;
import com.example.nophase.common.BaseCallBack;
import com.example.nophase.common.BaseResp;
import com.example.nophase.common.LoginManager;
import com.example.nophase.custom.CustomDialog;
import com.example.nophase.custom.MoneyDialog;
import com.example.nophase.custom.WarningDialog;
import com.example.nophase.entity.AdultMsgDTO;
import com.example.nophase.entity.ProjectDetailDTO;
import com.example.nophase.entity.SysUserVO;
import com.example.nophase.utils.HttpUtils;
import com.example.nophase.utils.WaterMarkBg;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Response;

public class WorkDetailFormActivity extends BaseActivity {


    @BindView(R.id.toolbar_btn)
    Button toolbarBtn;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.adult_no)
    TextView adultNo;
    @BindView(R.id.adult_name)
    TextView adultName;
    @BindView(R.id.adult_tel)
    TextView adultTel;
    @BindView(R.id.adult_position_iv)
    ImageView adultPositionIv;
    @BindView(R.id.adult_sumMoney)
    TextView adultSumMoney;
    @BindView(R.id.adult_totalMoney)
    TextView adultTotalMoney;
    @BindView(R.id.adult_limitMoney)
    TextView adultLimitMoney;
    @BindView(R.id.adult_resignMoney)
    TextView adultResignMoney;
    @BindView(R.id.adult_project_list)
    ListView adultProjectList;
    @BindView(R.id.adult_back)
    Button adultBack;
    @BindView(R.id.adult_save)
    Button adultSave;
    @BindView(R.id.adult_from_progressbar)
    ProgressBar adultFromProgressbar;
    @BindView(R.id.btn_layout)
    LinearLayout btnLayout;
    @BindView(R.id.content_layout)
    LinearLayout contentLayout;
    @BindView(R.id.adult_limit_Type)
    TextView adultLimitType;
    @BindView(R.id.applyfor_save_btn)
    Button applyforSaveBtn;
    @BindView(R.id.adult_moneyAdd)
    TextView adultMoneyAdd;

    private AdultMsgDTO applyForDTO;
    private List<ProjectDetailDTO> projectList;
    private FinanceProjectListAdapter adapter;
    private BigDecimal adultMoney;
    private String forkey;
    private String activityName;
    private String appType;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_adult_from);
        ButterKnife.bind(this);
        initData();
        setToolbar();
        SysUserVO sysUserVO = LoginManager.getUserInfo(this);
        String position = sysUserVO.getMoreInfo().getPosition();
        if (position.equals("总公司财务")) {
            btnLayout.setVisibility(View.GONE);
            adultPositionIv.setBackgroundResource(R.drawable.zgscw);
        } else {
            btnLayout.setVisibility(View.GONE);
            adultPositionIv.setBackgroundResource(R.drawable.znbmyg);
        }

        List<String> labels = new ArrayList<>();
        labels.add(sysUserVO.getUsername());
        contentLayout.setBackground(new WaterMarkBg(WorkDetailFormActivity.this, labels, -30, 18));
    }


    private void initData() {
        Intent intent = getIntent();
        forkey = intent.getStringExtra("forkey");
        System.out.println("forkey=======" + forkey);
        String type = intent.getStringExtra("type");
        if (type.equals("工资组")) {
            applyforSaveBtn.setVisibility(View.GONE);
        }
        HttpUtils.getInstance().setAuthToken(LoginManager.getToken(this));
        adultFromProgressbar.setVisibility(View.VISIBLE);
        Call<BaseResp<AdultMsgDTO<ProjectDetailDTO>>> call = HttpUtils.getInstance().getApiService(RequstCommonApi.class).loadTaskFrom("ANDROID", Integer.valueOf(forkey));
        call.enqueue(new BaseCallBack<BaseResp<AdultMsgDTO<ProjectDetailDTO>>>() {
            @Override
            public void onSuccess(Response<BaseResp<AdultMsgDTO<ProjectDetailDTO>>> response) throws Exception {
                adultFromProgressbar.setVisibility(View.GONE);
                applyForDTO = response.body().getData();
                activityName = applyForDTO.getActivitiname();
                adultMoney = applyForDTO.getAuditMoney();
                projectList = applyForDTO.getTyBusinessAppDetailVos();
                appType = applyForDTO.getAppType();
                adultTotalMoney.setText(getdivide(applyForDTO.getTotalMoney()));//累计批付金额
                adultLimitMoney.setText(getdivide(applyForDTO.getLimitMoney()));//限额
                adultName.setText(applyForDTO.getAppUserName());
                adultResignMoney.setText(getdivide(applyForDTO.getAuditMoney()));//批付金额
                adultMoneyAdd.setText(getdivide(applyForDTO.getMoneyAdd()));//累计申请金额
                adultTel.setText(applyForDTO.getAppUsertel());
                adultNo.setText(applyForDTO.getNo().toString());
                adultSumMoney.setText(getdivide(applyForDTO.getAppMoney()));
                if (type.equals("工资组")) {
                    adapter = new FinanceProjectListAdapter(projectList, WorkDetailFormActivity.this, false);
                } else {
                    adapter = new FinanceProjectListAdapter(projectList, WorkDetailFormActivity.this, true);
                }
                adultProjectList.setAdapter(adapter);
                adultProjectList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                    @Override
                    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                        String cause = projectList.get(position).getAppReason();
                        WarningDialog dialog = new WarningDialog(WorkDetailFormActivity.this, "申请原因", "请输入申请原因", "关闭");
                        dialog.setCanceledOnTouchOutside(false);
                        dialog.show();
                        dialog.setInputMsg(cause);
                        dialog.setClicklistener(new WarningDialog.ClickListenerInterface() {
                            @Override
                            public void doConfirm() {
                                dialog.dismiss();
                            }
                        });
                        return true;
                    }
                });
                if (!type.equals("工资组")) {
                    adultProjectList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            showMoneyDialog(position);
                        }
                    });
                }

            }

            @Override
            public void onFailure(String message) {

            }
        });


    }

    private void showMoneyDialog(int position) {
        MoneyDialog dialog = new MoneyDialog(WorkDetailFormActivity.this, "金额", "确定", "取消");
        dialog.setCanceledOnTouchOutside(false);
        dialog.setHintMsg("请输入批付金额");
        dialog.show();

        dialog.setClicklistener(new CustomDialog.ClickListenerInterface() {
            @Override
            public void doConfirm() {
                String money = dialog.getInputMsg();
                if (!money.equals("")) {


//                    int summoney = 0;
//                    for (ProjectDetailDTO item : projectList) {
//                        summoney += item.getFinanceAuditMoney().intValue();
//                    }
//                   adultMoney = new BigDecimal(summoney);
//                    adultResignMoney.setText(String.valueOf(adultMoney));
//                    applyForDTO.setFinanceAudltMoney(adultMoney);


                    projectList.get(position).setFinanceAuditMoney(new BigDecimal(money));
                    adapter.notifyDataSetChanged();
                    dialog.dismiss();
                } else {
                    dialog.dismiss();
                }

            }

            @Override
            public void doCancel() {
                dialog.dismiss();
            }
        });
    }

    /**
     * 修改金额提示框
     */
    private void setToolbar() {
        toolbar.setNavigationIcon(R.drawable.ic_left_black_24dp);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        getSupportActionBar().setHomeButtonEnabled(true);
        toolbarBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String processInstanceId = applyForDTO.getProcessInstanceId();
                Intent intent = new Intent(WorkDetailFormActivity.this, FlowRecordActivity.class);
                intent.putExtra("processInstanceId", processInstanceId);
                intent.putExtra("activityname", activityName);
                intent.putExtra("appType", appType);
                startActivity(intent);
            }
        });
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {

            case android.R.id.home:
                this.finish();
                return true;

        }
        return super.onOptionsItemSelected(item);
    }


    private String getdivide(BigDecimal val1) {
        BigDecimal val2 = new BigDecimal(10000);
        BigDecimal decimal = val1.divide(val2);
        if (decimal.intValue() >= 1) {
            //方式一
            DecimalFormat df1 = new DecimalFormat("0.00");
            String str1 = df1.format(decimal.doubleValue());
            return str1 + "万根";
        } else {
            DecimalFormat df2 = new DecimalFormat("0.0");
            String str2 = df2.format(val1.doubleValue());
            return str2 + "根";
        }
    }


    public void saveAdult() {
        adultFromProgressbar.setVisibility(View.VISIBLE);
        applyForDTO.setMainTicketId(Integer.valueOf(forkey));
        applyForDTO.setAccoutFinalStatus("已支付");
        applyForDTO.setTyBusinessAppDetails(projectList);
        applyForDTO.setTyBusinessAppDetailVos(projectList);


        int adultMoney = 0;
        for (ProjectDetailDTO item : projectList) {
            if(item.getFinanceAuditMoney() != null){
                adultMoney += item.getFinanceAuditMoney().intValue();
            }

        }
        if(adultMoney != 0){
            applyForDTO.setFinanceAudltMoney(new BigDecimal(adultMoney));
        }else{
            applyForDTO.setFinanceAudltMoney(applyForDTO.getAuditMoney());
        }


        Call<BaseResp<Object>> call = HttpUtils.getInstance().getApiService(RequstCommonApi.class).saveFinanceAdult("ANDROID", applyForDTO);
        call.enqueue(new BaseCallBack<BaseResp<Object>>() {
            @Override
            public void onSuccess(Response<BaseResp<Object>> response) throws Exception {
                adultFromProgressbar.setVisibility(View.GONE);
                String code = response.body().getCode();
                boolean success = response.body().getSuccess();
                if (code.equals("200") && success) {
                    Toast.makeText(WorkDetailFormActivity.this, "批付完成", Toast.LENGTH_LONG).show();
                    WorkDetailFormActivity.this.finish();
                }
            }

            @Override
            public void onFailure(String message) {

            }
        });
    }


    @OnClick(R.id.applyfor_save_btn)
    public void onViewClicked() {
        saveAdult();
    }
}
